package com.heer.gymnasium.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.heer.gymnasium.R;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.fragment.BaseFragment;
import com.heer.gymnasium.fragment.MainAccessFragment;
import com.heer.gymnasium.fragment.MainHomeFragment;
import com.heer.gymnasium.fragment.MainMineFragment;
import com.heer.gymnasium.fragment.MainOrderFragment;
import com.heer.gymnasium.service.MessageService;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

import static com.heer.gymnasium.event.EventConstant.CREATE_ORDER;
import static com.heer.gymnasium.event.EventConstant.MINE_TO_ORDER;
import static com.heer.gymnasium.event.EventConstant.USER_NEW_MSG;

/**
 * Created by heer on 17/3/28.
 */

public class MainActivity extends BaseActivity {
    @BindView(R.id.layout_content)
    FrameLayout layoutContent;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;

    private ImageView iv_cule;

    private static final String[] TITLES = new String[]{"首页", "我的订单", "出入场", "我的"};
    private static final Integer[] IMAGES = new Integer[]{R.drawable.selector_main_tab_1, R.drawable.selector_main_tab_2, R.drawable.selector_main_tab_3, R.drawable.selector_main_tab_4};
    private List<String> mDataList = Arrays.asList(TITLES);
    private List<Integer> mDataImgList = Arrays.asList(IMAGES);
    private List<Fragment> mFragments = new ArrayList<>();
    public FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
    private int index = 0;
    Intent i;
    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
      //  if (getIntent().hasExtra("index"))
            index = getIntent().getIntExtra("index", 0);
        i=new Intent(mContext, MessageService.class);
        startService(i);
    }

    @Override
    protected void initView() {
        super.initView();

        initFragments();
        initMagicIndicator();
        switchPages(index);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(i);
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void eventBus(BaseEvent event) {
        if (TextUtils.equals(event.getId(), MINE_TO_ORDER)) {
            mFragmentContainerHelper.handlePageSelected(1);
            switchPages(1);
        }else if(TextUtils.equals(event.getId(), USER_NEW_MSG)){
            iv_cule.setVisibility(View.VISIBLE);
        }
    }

    private void initFragments() {
        BaseFragment orderFragment = new MainOrderFragment();
        BaseFragment accessFragment = new MainAccessFragment();
        BaseFragment mineFragment = new MainMineFragment();
        BaseFragment homeFragment = new MainHomeFragment();
        mFragments.add(homeFragment);
        mFragments.add(orderFragment);
        mFragments.add(accessFragment);
        mFragments.add(mineFragment);
    }

    private void initMagicIndicator() {
        final CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

                // load custom layout
                final View customLayout = LayoutInflater.from(context).inflate(R.layout.item_main_tab, null);
                final ImageView titleImg = (ImageView) customLayout.findViewById(R.id.image);
                final TextView titleText = (TextView) customLayout.findViewById(R.id.tv_desc);
                final ImageView imageclue= (ImageView) customLayout.findViewById(R.id.clue);
                titleImg.setImageResource(mDataImgList.get(index));
                titleText.setText(mDataList.get(index));
                commonPagerTitleView.setContentView(customLayout);

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        titleText.setTextColor(mAppHelper.getResources().getColor(R.color.colorPrimary));
                        titleImg.setSelected(true);
                        imageclue.setVisibility(View.GONE);
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        titleText.setTextColor(mAppHelper.getResources().getColor(R.color.colorTextNormal));
                        titleImg.setSelected(false);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mFragmentContainerHelper.handlePageSelected(index);
                        switchPages(index);
                    }
                });
                if (index==3)
                {
                    iv_cule=imageclue;
                }

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;    // 没有指示器，因为title的指示作用已经很明显了
            }
        });

        magicIndicator.setNavigator(commonNavigator);
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator);
        mFragmentContainerHelper.handlePageSelected(index, false);
    }

    public void switchPages(int index) {

        titleBuilder.setLeftImage(0);
        titleBuilder.setRightImage(0);
        if (index != 0) {
            titleBuilder.setTitleText(TITLES[index]);
            titleBuilder.setTitleBackground(0);
        } else {
            titleBuilder.setTitleText("");
            titleBuilder.setTitleBackground(R.mipmap.ic_logo_text);
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment;
        for (int i = 0, j = mFragments.size(); i < j; i++) {
            if (i == index) {
                continue;
            }
            fragment = mFragments.get(i);
            if (fragment.isAdded()) {
                fragmentTransaction.hide(fragment);
            }
        }
        fragment = mFragments.get(index);
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.layout_content, fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

   @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getIntent().hasExtra("index")) {
            index = getIntent().getIntExtra("index", 0);
            switchPages(index);
            mFragmentContainerHelper.handlePageSelected(index, false);
        }
    }


}
